package cn.le.config;

import cn.le.factory.HandlerFactory;
import cn.le.inf.HandlerCode;
import cn.le.inf.NettyHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class HandlerConfig {

    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    public void nettyHandlers(){
        List<NettyHandler> list = new ArrayList<>(applicationContext.getBeansOfType(NettyHandler.class).values());
        if (CollectionUtils.isEmpty(list)){
            throw new RuntimeException("netty handler is null");
        }
        Map<Integer,NettyHandler> map = new HashMap<>();
        list.forEach(nettyHandler -> {
            int code = nettyHandler.getClass().getAnnotation(HandlerCode.class).value();
            map.put(code,nettyHandler);
        });
        HandlerFactory.setHandlerMap(map);
    }
}
